{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from numpy import genfromtxt\n",
    "import matplotlib.pyplot as plt  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 载入数据\n",
    "data = np.genfromtxt(\"data.csv\", delimiter=\",\")\n",
    "x_data = data[:,0,np.newaxis]\n",
    "y_data = data[:,1,np.newaxis]\n",
    "plt.scatter(x_data,y_data)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(np.mat(x_data).shape)\n",
    "print(np.mat(y_data).shape)\n",
    "# 给样本添加偏置项\n",
    "X_data = np.concatenate((np.ones((100,1)),x_data),axis=1)\n",
    "print(X_data.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(X_data[:3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 标准方程法求解回归参数\n",
    "def weights(xArr, yArr):\n",
    "    xMat = np.mat(xArr)\n",
    "    yMat = np.mat(yArr)\n",
    "    xTx = xMat.T*xMat # 矩阵乘法\n",
    "    # 计算矩阵的值,如果值为0，说明该矩阵没有逆矩阵\n",
    "    if np.linalg.det(xTx) == 0.0:\n",
    "        print(\"This matrix cannot do inverse\")\n",
    "        return\n",
    "    # xTx.I为xTx的逆矩阵\n",
    "    ws = xTx.I*xMat.T*yMat\n",
    "    return ws"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ws = weights(X_data,y_data)\n",
    "print(ws)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 画图\n",
    "x_test = np.array([[20],[80]])\n",
    "y_test = ws[0] + x_test*ws[1]\n",
    "plt.plot(x_data, y_data, 'b.')\n",
    "plt.plot(x_test, y_test, 'r')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
